# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/2/18
# python-version    : Python 3.7.0
# description       : 小程序接口相关

import httplib2
from flask import Flask, jsonify, request, session
from com.articles.microapp.utils.constants import CommonConstants
from com.articles.microapp.config.config import CONFIG
from com.articles.microapp.utils.cache_utils import Cache


class WechatInterface(object):
    consts = CommonConstants()
    config = CONFIG.config()
    cache = Cache()

    def __init__(self, app=Flask(__name__)):
        app.add_url_rule('/login', view_func=self.login)
        app.add_url_rule('/getUserInfo', view_func=self.get_userinfo, methods=['GET'])

    def login(self):
        return 'success'

    def get_userinfo(self):
        code = request.args.get('code')
        appid = self.config.get_value(self.consts.WX_MICRO_APP, self.consts.WX_APPID)
        app_secret = self.config.get_value(self.consts.WX_MICRO_APP, self.consts.WX_APPSECRET)
        url = str(self.config.get_value(self.consts.WX_MICRO_APP, self.consts.WX_AUTHORIZATION_URL)) \
            .replace(self.consts.WX_APPID, appid) \
            .replace(self.consts.WX_APPSECRET, app_secret) \
            .replace(self.consts.WX_JSCODE, code)
        conn = httplib2.HTTPSConnectionWithTimeout(
            self.config.get_value(self.consts.WX_MICRO_APP, self.consts.WX_IF_HOST))
        conn.request(method="GET", url=url)
        resp = conn.getresponse()
        data = str(resp.read(), encoding='utf-8')
        resp_data = eval(data)
        # print(resp_data)
        if not resp_data.get("errcode"):
            self.cache.set(resp_data.get('session_key'), resp_data, resp_data.get('expires_in'))
            print(self.cache.get(resp_data.get("session_key")))
        return data
